package com.atguigu.gulimail.product.service.impl;

import com.atguigu.common.constant.ProductConstant;
import com.atguigu.gulimail.product.dao.AttrAttrgroupRelationDao;
import com.atguigu.gulimail.product.dao.AttrGroupDao;
import com.atguigu.gulimail.product.dao.CategoryDao;
import com.atguigu.gulimail.product.entity.AttrAttrgroupRelationEntity;
import com.atguigu.gulimail.product.entity.AttrGroupEntity;
import com.atguigu.gulimail.product.entity.CategoryEntity;
import com.atguigu.gulimail.product.service.CategoryService;
import com.atguigu.gulimail.product.vo.AttrEntityVo;
import com.atguigu.gulimail.product.vo.AttrRespVo;
import com.atguigu.gulimail.product.vo.AttrVo;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;

import com.atguigu.gulimail.product.dao.AttrDao;
import com.atguigu.gulimail.product.entity.AttrEntity;
import com.atguigu.gulimail.product.service.AttrService;
import org.springframework.transaction.annotation.Transactional;


@Service("attrService")
public class AttrServiceImpl extends ServiceImpl<AttrDao, AttrEntity> implements AttrService {

	@Autowired
	private AttrAttrgroupRelationDao relationDao;
	@Autowired
	private AttrGroupDao attrGroupDao;
	@Autowired
	private CategoryDao categoryDao;
	@Autowired
	private CategoryService categoryService;
	


    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<AttrEntity> page = this.page(
                new Query<AttrEntity>().getPage(params),
                new QueryWrapper<AttrEntity>()
        );

        return new PageUtils(page);
    }


	@Override
	public void saveDetail(AttrEntityVo attrvo) {
		AttrEntity attrEntity = new AttrEntity();
		BeanUtils.copyProperties(attrvo, attrEntity);
		this.save(attrEntity);
		// 级联
		if(attrvo.getAttrType() == ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode() &&
			attrvo.getAttrGroupId() != null
		){
			AttrAttrgroupRelationEntity relationEntity = new AttrAttrgroupRelationEntity();
			relationEntity.setAttrGroupId(attrvo.getAttrGroupId());
			relationEntity.setAttrId(attrEntity.getAttrId());
			relationDao.insert(relationEntity);
		}
	}

	@Override
	public PageUtils queryBasePage(Map<String, Object> params, Long categoryId, String attrType) {
		String key = (String) params.get("key");
		QueryWrapper<AttrEntity> queryWrapper = new QueryWrapper<AttrEntity>()
								.eq("attr_type", "base".equalsIgnoreCase(attrType) ? ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode() : ProductConstant.AttrEnum.ATTR_TYPE_SALE.getCode());
		if(categoryId != 0) {
			queryWrapper.eq("catelog_id", categoryId);
		}


		if(StringUtils.isNotBlank(key)) {
			queryWrapper.and((obj)->{
				obj.eq("attr_id", key).or().like("attr_name", key);
			});
		}


		IPage<AttrEntity> page = this.page(
			new Query<AttrEntity>().getPage(params),
			queryWrapper
		);

		PageUtils pageUtils = new PageUtils(page);
		List<AttrEntity> records = page.getRecords();

		List<AttrRespVo> attrEntityVoList = records.stream().map((attrEntity) -> {
			AttrRespVo attrRepVo = new AttrRespVo();
			BeanUtils.copyProperties(attrEntity, attrRepVo);
			if("base".equalsIgnoreCase(attrType)) {
				AttrAttrgroupRelationEntity attrAttrgroupRelationEntity = relationDao.selectOne(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", attrEntity.getAttrId()));
				if(attrAttrgroupRelationEntity != null) {
					AttrGroupEntity attrGroupEntity = attrGroupDao.selectById(attrAttrgroupRelationEntity.getAttrGroupId());
					attrRepVo.setGroupName(attrGroupEntity.getAttrGroupName());
				}
			}
			CategoryEntity categoryEntity = categoryDao.selectById(attrEntity.getCatelogId());
			attrRepVo.setCatelogName(categoryEntity!=null?categoryEntity.getName():"");
			return attrRepVo;
		}).collect(Collectors.toList());

		pageUtils.setList(attrEntityVoList);

		return pageUtils;
	}

	@Override
	public AttrRespVo getAttrInfo(Long attrId) {
		AttrEntity attrEntity = this.getById(attrId);
		AttrRespVo attrRespVo = new AttrRespVo();
		BeanUtils.copyProperties(attrEntity, attrRespVo);
		if(attrEntity.getAttrType() == ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode()) {
			// 设置分组信息
			AttrAttrgroupRelationEntity attrAttrgroupRelationEntity = relationDao.selectOne(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", attrId));
			if(attrAttrgroupRelationEntity!=null){
				attrRespVo.setAttrGroupId(attrAttrgroupRelationEntity.getAttrGroupId());
				AttrGroupEntity attrGroupEntity = attrGroupDao.selectById(attrAttrgroupRelationEntity.getAttrGroupId());
				attrRespVo.setGroupName(attrGroupEntity != null ? attrGroupEntity.getAttrGroupName() : "");
			}
		}
		// 获取分类信息
		Long catelogId = attrEntity.getCatelogId();
		Long[] catelogPath = categoryService.findCatelogPath(catelogId);
		attrRespVo.setCatelogPath(catelogPath);

		return attrRespVo;
	}

	@Transactional(rollbackFor = Exception.class)
	@Override
	public void updateAttr(AttrVo attr) {
		AttrEntity attrEntity = new AttrEntity();
		BeanUtils.copyProperties(attr,attrEntity);
		this.updateById(attrEntity);
		if(attr.getAttrType() == ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode()) {
			//1、修改分组关联
			AttrAttrgroupRelationEntity relationEntity = new AttrAttrgroupRelationEntity();
			relationEntity.setAttrGroupId(attr.getAttrGroupId());
			relationEntity.setAttrId(attr.getAttrId());
			Integer count = relationDao.selectCount(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", attr.getAttrId()));
			if(count>0){
				relationDao.update(relationEntity,new UpdateWrapper<AttrAttrgroupRelationEntity>().eq("attr_id",attr.getAttrId()));

			}else{
				relationDao.insert(relationEntity);
			}
		}

	}

	@Override
	public List<AttrEntity> getByAttrGroupId(Long attrgroupId) {
    	// 先从 pms_attr_attrgroup_relation 表中获取数据
		QueryWrapper<AttrAttrgroupRelationEntity> queryWrapper = new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_group_id", attrgroupId);
		List<AttrAttrgroupRelationEntity> attrAttrgroupRelationEntities = relationDao.selectList(queryWrapper);
		List<Long> collect = attrAttrgroupRelationEntities.stream().map(attrAttrgroupRelationEntity -> {
			return attrAttrgroupRelationEntity.getAttrId();
		}).collect(Collectors.toList());
		Collection<AttrEntity> attrEntities = this.listByIds(collect);
		return (List<AttrEntity>) attrEntities;
	}
}